package cn.smile.business.basic.impl;

import cn.smile.bean.dto.basic.MyShopDTO;
import cn.smile.bean.entity.basic.MyShop;
import cn.smile.bean.form.basic.shop.SavePositionForm;
import cn.smile.bean.form.basic.shop.SaveShopForm;
import cn.smile.business.basic.IMyShopService;
import cn.smile.business.basic.IUserShopService;
import cn.smile.commons.constant.NumberConstant;
import cn.smile.commons.constant.ShopConstant;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.commons.exceptions.BusinessException;
import cn.smile.commons.response.MyResponseCode;
import cn.smile.repository.basic.MyShopMapper;
import cn.smile.utils.BeanCopy;
import cn.smile.utils.PasswordUtil;
import cn.smile.utils.UserUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MyShopServiceImpl extends BaseServiceImpl<MyShopMapper, MyShop> implements IMyShopService {
    @Resource
    private IUserShopService userToShopService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String initShop(String managerId) {
        log.info("[MyShopServiceImpl].[initShop] ------> 初始化店铺信息 Start");
        MyShop entity = this.getDefaultShop();
        entity.setShopManagerId(managerId);
        super.addBaseCol(entity);
        //生成店铺邀请码
        String code = this.randomShopCode();
        entity.setShopCode(code);
        int insertNum = baseMapper.insert(entity);
        if (insertNum > NumberConstant.ZERO) {
            userToShopService.bindShop(managerId, code, 1001);
        }
        log.info("[MyShopServiceImpl].[initShop] ------> 初始化店铺信息 End, insertNum = {} code = {}", insertNum, code);
        return insertNum > NumberConstant.ZERO ? code : null;
    }

    @Override
    public Boolean bindShop(String userId, String shopCode) {
        // 校验店铺码是否存在
        List<MyShop> shopList = baseMapper.selectList(new QueryWrapper<MyShop>().lambda().eq(MyShop::getDeleted, Boolean.FALSE).eq(MyShop::getShopCode, shopCode));
        if (CollectionUtils.isEmpty(shopList)) {
            throw new BusinessException(MyResponseCode.SHOP_CODE_DATA_NONE);
        }
        int dicValue = UserUtil.getUserInfo().getId().equals(shopList.get(NumberConstant.ZERO).getShopManagerId()) ? 1001 : 1007;
        return userToShopService.bindShop(userId, shopCode, dicValue);
    }

    @Override
    public Boolean bindShop(String shopCode) {
        return this.bindShop(UserUtil.getUserInfo().getId(), shopCode);
    }

    @Override
    public MyShopDTO getMyShop() {
        log.info("[MyShopServiceImpl].[getMyShop] ------> 查询我的店铺信息 Start");
        String myShopCode = userToShopService.getMyShopCode(UserUtil.getUserInfo().getId());
        MyShop entity;
        if (!ObjectUtils.isEmpty(myShopCode)) {
            entity = baseMapper.selectOne(new QueryWrapper<MyShop>().lambda().eq(MyShop::getShopCode, myShopCode).eq(MyShop::getDeleted, Boolean.FALSE));
        } else {
            entity = this.getDefaultShop();
        }
        MyShopDTO dto = BeanCopy.copyBean(entity, MyShopDTO.class);
        log.info("[MyShopServiceImpl].[getMyShop] ------> 查询我的店铺信息 End");
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveShop(SaveShopForm form) {
        log.info("[MyShopServiceImpl].[saveShop] ------> 保存店铺信息 Start, form = {}", JSON.toJSONString(form));
        boolean isAdd = ObjectUtils.isEmpty(form.getShopCode());
        MyShop entity = BeanCopy.copyBean(form, MyShop.class);
        if (isAdd) {
            entity.setShopCode(this.randomShopCode());
            entity.setShopManagerId(UserUtil.getUserInfo().getId());
            super.addBaseCol(entity);
        } else {
            super.updateBaseCol(entity);
        }
        int updateNum;
        if (isAdd) {
            updateNum = baseMapper.insert(entity);
        } else {
            updateNum = baseMapper.update(entity, new QueryWrapper<MyShop>().lambda().eq(MyShop::getShopCode, form.getShopCode()));
        }
        log.info("[MyShopServiceImpl].[saveShop] ------> 保存店铺信息 End, updateNum = {}", updateNum);
        return updateNum > NumberConstant.ZERO;
    }

    @Override
    public Map<String, Integer> getUserIds(String shopCode) {
        return userToShopService.getUserIdsByCode(shopCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean savePosition(SavePositionForm form) {
        return userToShopService.savePosition(form);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean relieveBind(String userId) {
        return userToShopService.relieveBind(userId);
    }

    /**
     * 生成不重复的店铺编码
     *
     * @return 店铺编码
     */
    private String randomShopCode() {
        //获取随机Code (全部字母大写)
        String code = PasswordUtil.randomLoginId(NumberConstant.EIGHT).toLowerCase();
        List<MyShop> shopList = baseMapper.selectList(new QueryWrapper<MyShop>().lambda().eq(MyShop::getShopCode, code).eq(MyShop::getDeleted, Boolean.FALSE));
        if (!CollectionUtils.isEmpty(shopList)) {
            code = this.randomShopCode();
        }
        return code;
    }

    /**
     * 初始化一个默认店铺信息
     *
     * @return 初始化结果对象
     */
    private MyShop getDefaultShop() {
        MyShop entity = new MyShop();
        //写入默认信息
        entity.setShopName(ShopConstant.DEFAULT_SHOP_NAME);
        entity.setShopAddress(ShopConstant.DEFAULT_SHOP_ADDRESS);
        entity.setShopPhone(ShopConstant.DEFAULT_SHOP_PHONE);
        entity.setOpeningHoursStart(ShopConstant.DEFAULT_SHOP_TIME_START);
        entity.setOpeningHoursEnd(ShopConstant.DEFAULT_SHOP_TIME_END);
        return entity;
    }
}
